import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Spin, Pagination } from 'antd';
import { ApiService } from '../services/api';
import './SolutionsPage.css';

const SolutionsPage = () => {
  const navigate = useNavigate();
  const [solutions, setSolutions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const pageSize = 10;

  // 获取解决方案列表
  useEffect(() => {
    const fetchSolutions = async () => {
      try {
        setLoading(true);
        setError(null);

        const response = await ApiService.getSolutionsListPage(currentPage, pageSize);

        if (response.code === '0000' && response.data) {
          // 转换API数据格式
          const formattedSolutions = response.data.map(item => ({
            id: item.newsId,
            title: item.newsTitle,
            description: '', // API没有返回描述，可以后续扩展
            features: [], // API没有返回特性列表，可以后续扩展
            image: item.picUrl || '💡', // 如果没有图片URL，使用默认图标
            industry: '解决方案', // 默认分类
            date: item.newTime ? new Date(item.newTime).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit'
            }) : '',
            content: item.newsItemContentBind || '' // 富文本内容
          }));

          setSolutions(formattedSolutions);
          setTotal(response.total || 0);
        } else {
          setError('获取解决方案失败');
        }
      } catch (err) {
        console.error('获取解决方案失败:', err);
        setError('网络请求失败');
      } finally {
        setLoading(false);
      }
    };

    fetchSolutions();
  }, [currentPage]);

  // 处理分页变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
  };

  // 处理解决方案点击
  const handleSolutionClick = (solutionId) => {
    navigate(`/solutions/${solutionId}`);
  };

  if (loading) {
    return (
      <div className="solutions-page">
        <div className="container">
          <div className="page-header">
            <h1>解决方案</h1>
            <p>为不同行业提供定制化的科技解决方案，助力企业数字化转型</p>
          </div>
          <div className="loading-container">
            <Spin size="large" />
            <p>加载解决方案中...</p>
          </div>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="solutions-page">
        <div className="container">
          <div className="page-header">
            <h1>解决方案</h1>
            <p>为不同行业提供定制化的科技解决方案，助力企业数字化转型</p>
          </div>
          <div className="error-container">
            <p>{error}</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="solutions-page">
      <div className="container">
        <div className="page-header">
          <h1>解决方案</h1>
          <p>为不同行业提供定制化的科技解决方案，助力企业数字化转型</p>
        </div>

        <div className="solutions-grid">
          {solutions.length > 0 ? (
            solutions.map(solution => (
              <div key={solution.id} className="solution-card" onClick={() => handleSolutionClick(solution.id)}>
                <div className="solution-image">
                  {solution.image.startsWith('http') ? (
                    <img src={solution.image} alt={solution.title} className="solution-img" />
                  ) : (
                    <div className="solution-icon">{solution.image}</div>
                  )}
                </div>
                <div className="solution-content">
                  <h3 className="solution-title">{solution.title}</h3>
                  <div className="solution-meta">
                    <span className="solution-date">{solution.date}</span>
                  </div>
                </div>
              </div>
            ))
          ) : (
            <div className="no-solutions">
              <p>暂无解决方案</p>
            </div>
          )}
        </div>

        {/* 分页组件 */}
        {total > 0 && (
          <div className="pagination-container">
            <Pagination
              current={currentPage}
              total={total}
              pageSize={pageSize}
              onChange={handlePageChange}
              showSizeChanger={false}
              showTotal={(total, range) =>
                `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
              }
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default SolutionsPage;
